<?php
namespace app\api\controller\kuyou\applet;
use think\Db;
class Salesprofit extends Common
{
    public function index()
    {
        if ($this->request->isPost()) {
            $where = [];$map = [];
            $code = $this->request->post('purchase_code');
            if(!empty($code)){
                $where['i.purchase_code'] = ['like','%'.$code.'%'];
            }
            $purchase_time = $this->request->post('purchase_time');
            if(!empty($purchase_time)){
                $str = explode('~',$purchase_time);
                if(isset($str[0]) && isset($str[1])){
                    $where['i.purchase_time'] = ["BETWEEN", [strtotime($str[0]),strtotime($str[1])]];
                }
            }
            $customers_id = $this->request->post('customers_id');
            if(!empty($customers_id)){
                $where['i.customers_id'] = $customers_id;
            }
            $sale_user = $this->request->post('sale_user');
            if(!empty($sale_user)){
                $where['i.sale_user'] = $sale_user;
            }
            $goods_code = $this->request->post('goods_code');
            if(!empty($goods_code)){
                $where['i.goods_code'] = $goods_code;
            }

            $page = $this->request->post('page');
            $page = empty($page)?1:$page;
            $limit = $this->request->post('limit');
            $limit = empty($limit)?config('app_limit'):$limit;
            $app_page = config('app_page');
        $app_page = $app_page===false?false:true;
            $pageStatus = true;
            if($app_page){
                if($page<0){
                    $pageStatus = false;
                }
            }

            if($pageStatus){
                $list = Db::name('kuyou_goods_sales_profit')->alias('i')
                    ->join('kuyou_customers s','s.id=i.customers_id')
                    ->where($where)
                    ->page($page,$limit)
                    ->field('i.id,FROM_UNIXTIME(i.purchase_time,\'%Y-%m-%d\') as purchase_time,i.customers_id,i.sale_user,i.preparation_id,i.examine_id,
                i.purchase_code,i.purchase_type,i.number,i.amount,i.all_money,i.tax_money,i.money_tax_price,i.sales_cost,i.preferential_money,
                i.purchase_money,i.real_money,i.customers_money,i.need_money,i.pay_money,
                s.customer_name as s_name')
                    ->select();
            }else{
                $list = Db::name('kuyou_goods_sales_profit')->alias('i')
                    ->join('kuyou_customers s','s.id=i.customers_id')
                    ->where($where)
                    ->field('i.id,FROM_UNIXTIME(i.purchase_time,\'%Y-%m-%d\') as purchase_time,i.customers_id,i.sale_user,i.preparation_id,i.examine_id,
                i.purchase_code,i.purchase_type,i.number,i.amount,i.all_money,i.tax_money,i.money_tax_price,i.sales_cost,i.preferential_money,
                i.purchase_money,i.real_money,i.customers_money,i.need_money,i.pay_money,
                s.customer_name as s_name')
                    ->select();
            }
            $row_count = Db::name('kuyou_goods_sales_profit')->alias('i')
                ->join('kuyou_customers s','s.id=i.customers_id')
                ->where($where)
                ->count();


            if($row_count>0){
                $checkdate = Db::name('kuyou_checkout')->order(['checkdate'=>'DESC'])->value('checktime');
                $enable_time = Db::name('kuyou_sets')->where(['name'=>'enable_time'])->value('value');
                $map = [];
                if(!empty($checkdate)){
                    $map['purchase_time'] = ['>',$checkdate];
                }
                $price_decimal = Db::name('kuyou_sets')->where(['name'=>'price_decimal'])->value('value');
                $valuation_set= Db::name('kuyou_sets')->where(['name'=>'valuation'])->value('value');//计算方法
                $stores_set= Db::name('kuyou_sets')->where(['name'=>'stores'])->value('is_checked');//是否分仓
                if($valuation_set!=2){
                    $valuation_set = 1;
                }
                if($stores_set!=1){
                    $stores_set = 0;
                }
                $price_taxes= Db::name('kuyou_sets')->where(['name'=>'price_taxes'])->value('is_checked');
                $taxes_set= Db::name('kuyou_sets')->where(['name'=>'taxes'])->field('value,is_checked')->find();

                $sort = 'purchase_time';$order='ASC';
                $lists = Db::name('kuyou_goods_sales_profit')
                    ->where($map)
                    ->order($sort, $order)
                    ->select();
                $goods_info = [];
                $stores_ids = Db::name('kuyou_stores')->where(['status'=>'1'])->column('id');

                foreach ($lists as $list_k=>$list_v){
                    $cost_all = 0;$pay_money = 0;
                    $info = Db::name('kuyou_goods_sales_info')->where(['purchase_code'=>$list_v['purchase_code']])->field('pay_money,basic_nmber,goods_code,stores_id,purchase_time')->select();
                    foreach ($info as $info_k=>$info_v){
                        $goods = Db::name('kuyou_goods')->where(['goods_code'=>$info_v['goods_code']])->find();
                        if(!isset($goods_info[$info_v['goods_code']])){
                            $where = [];
                            if($stores_set==1){
                                $where['stores_id'] = ['in',$stores_ids];
                            }else{
                                $where['stores_id'] = $info_v['stores_id'];
                            }
                            $where['goods_code'] = $info_v['goods_code'];

                            if(empty($checkdate)){
                                $start_time = strtotime($enable_time);
                                $end_time = strtotime(date('Y-m-d',$info_v['purchase_time']).' 23:59:59');
                                $wheretime['start_time'] = $start_time;
                                $wheretime['end_time'] = $end_time;
                                if(!empty($wheretime)){
                                    $where['purchase_time'] = ['between',[$wheretime['start_time'],time()]];
                                }
                                if($valuation_set==1){
                                    $purchase_info = Db::name('kuyou_goods_purchase_info')->where($where)->group('purchase_time')
                                        ->field('purchase_time,sum(basic_nmber) as basic_nmber,sum(all_money) as all_money')
                                        ->order(['purchase_time'=>'ASC'])->select();
                                }else{
                                    $purchase_info = Db::name('kuyou_goods_purchase_info')->where($where)
                                        ->field('purchase_time,basic_nmber,all_money')
                                        ->order(['purchase_time'=>'ASC','purchase_code'=>'ASC'])->select();
                                }
                            }else{
                                $checkout_id = Db::name('kuyou_checkout')->order(['checkdate'=>'DESC'])->value('id');
                                $purchase_more = Db::name('kuyou_checkout_info')->where([
                                    'checkout_id'=>$checkout_id,
                                    'goods_code'=>$info_v['goods_code'],
                                ])->find();
                                $purchase_infos = Db::name('kuyou_goods_purchase')->where(['id'=>$purchase_more['purchase_id']])->find();

                                $start_time = $checkdate;
                                $end_time = strtotime(date('Y-m-d',$info_v['purchase_time']).' 23:59:59');
                                $wheretime['start_time'] = $start_time;
                                $wheretime['end_time'] = $end_time;
                                if(!empty($wheretime)){
                                    $where['purchase_time'] = ['between',[$wheretime['start_time'],time()]];
                                }
                                if($valuation_set==1){
                                    $purchase_info = Db::name('kuyou_goods_purchase_info')->where($where)->group('purchase_time')
                                        ->field('purchase_time,sum(basic_nmber) as basic_nmber,sum(all_money) as all_money')
                                        ->order(['purchase_time'=>'ASC'])->select();
                                    if(!empty($purchase_more)){
                                        foreach ($purchase_info as $purchase_info_k=>$purchase_info_v){
                                            if($purchase_info_v['purchase_time']==$purchase_more['purchase_time']){
                                                $purchase_info[$purchase_info_k]['basic_nmber'] = (float)$purchase_more['av_basic_nmber'];
                                                $purchase_info[$purchase_info_k]['all_money'] = (float)$purchase_more['av_all_money'];
                                            }
                                        }
                                    }
                                }else{
                                    if(empty($purchase_more)){
                                        $purchase_info = Db::name('kuyou_goods_purchase_info')->where($where)
                                            ->field('purchase_time,basic_nmber,all_money')
                                            ->order(['purchase_time'=>'ASC','purchase_code'=>'ASC'])->select();
                                    }else{
                                        $where['purchase_code'] = ['>=',$purchase_infos['purchase_code']];
                                        $purchase_info = Db::name('kuyou_goods_purchase_info')->where($where)
                                            ->field('id,purchase_time,basic_nmber,all_money')
                                            ->order(['purchase_time'=>'ASC','purchase_code'=>'ASC'])->select();
                                        foreach ($purchase_info as $purchase_info_k=>$purchase_info_v){
                                            if($purchase_info_v['id']==$purchase_more['purchase_id']){
                                                $purchase_info[$purchase_info_k]['basic_nmber'] = (float)$purchase_more['basic_nmber'];
                                                $purchase_info[$purchase_info_k]['all_money'] = (float)$purchase_more['all_money'];
                                            }
                                        }
                                    }
                                }
                            }


                            $where = [];
                            $where['goods_code'] = $info_v['goods_code'];
                            $where['stores_id'] = ['in',$stores_ids];
                            if(!empty($wheretime)){
                                $where['createtime'] = ['between',[$wheretime['start_time'],time()]];
                            }
                            //期初
                            $period = Db::name('kuyou_goods_period')->where($where)->field('period as basic_nmber,price as all_money,createtime as purchase_time')->find();
                            if(!empty($period)){
                                $period['purchase_time'] = strtotime(date('Y-m-d',$period['purchase_time']));
                                if($valuation_set==1){
                                    $status = true;
                                    foreach ($purchase_info as $purchase_info_k=>$purchase_info_v){
                                        if($purchase_info_v['purchase_time']==$period['purchase_time']){
                                            $status = false;
                                            $purchase_info[$purchase_info_k]['basic_nmber'] += $period['basic_nmber'];
                                            $purchase_info[$purchase_info_k]['all_money'] += $period['all_money'];
                                        }
                                    }
                                    if($status){
                                        $purchase_info[] = $period;
                                        $purchase_info = (new Commons())->arraySequence($purchase_info,'purchase_time','SORT_ASC');
                                    }
                                }else{
                                    $purchase_infos = [];
                                    $purchase_infos[] = $period;
                                    foreach ($purchase_info as $k=>$v){
                                        $purchase_infos[] = $v;
                                    }
                                    $purchase_info = $purchase_infos;
                                }
                            }

                            if($goods){
                                $where = [];
                                $where['goods_id'] = $goods['id'];
                                $where['stores_id'] = ['in',$stores_ids];
                                if(!empty($wheretime)){
                                    $where['purchase_time'] = ['between',[$wheretime['start_time'],time()]];
                                }
                                //成本调整
                                $adjustment_money = 0;
                                $adjustment = Db::name('kuyou_adjustment_info')->where($where)->select();
                                foreach ($adjustment as $adjustment_k=>$adjustment_v){
                                    $advance_rate = 1;//单位换算进率
                                    if($adjustment_v['goods_unit']!=$goods['unit_id']){
                                        $unit = Db::name('kuyou_unit_conversion')->where(['main_unit'=>$goods['unit_id'],'vice_unit'=>$adjustment_v['goods_unit']])->value('advance_rate');
                                        if(!empty($unit) && $unit>0){
                                            $advance_rate = $unit;
                                        }
                                    }
                                    $money = $adjustment_v['money']/$advance_rate;//换算后的调整成本
                                    $adjustment[$adjustment_k]['purchase_time'] = strtotime(date('Y-m-d',$adjustment_v['purchase_time']));
                                    $adjustment[$adjustment_k]['all_money'] = $adjustment_v['money'];
                                }
                                foreach ($adjustment as $adjustment_k=>$adjustment_v){
                                    foreach ($purchase_info as $purchase_info_k=>$purchase_info_v){
                                        if($purchase_info_v['purchase_time']==$adjustment_v['purchase_time']){
                                            $purchase_info[$purchase_info_k]['all_money'] += $adjustment_v['all_money'];
                                        }
                                    }
                                }
                                //成本调整结束
                            }
                        }else{
                            $purchase_info = $goods_info[$info_v['goods_code']];
                        }

                        $cost = (new Commons())->getCost_Price($goods,'',$info_v['basic_nmber'],$purchase_info,$price_taxes,$valuation_set,$taxes_set);

                        if(isset($cost['purchase_info'])){
                            $goods_info[$info_v['goods_code']] = $cost['purchase_info'];
                            $purchase_info = $goods_info[$info_v['goods_code']];
                            $cost = $cost['cost'];
                        }
                        $cost_all += $cost*$info_v['basic_nmber'];
                        $pay_money += $info_v['pay_money'];
                    }
                    $lists[$list_k]['pay_money'] = $pay_money;
                    if($list_v['purchase_type']==2){
                        $cost_all = -$cost_all;
                    }
                    $lists[$list_k]['sales_cost'] = round($cost_all,$price_decimal);
                    $lists[$list_k]['profit'] = round($list_v['all_money']-$cost_all,$price_decimal);
                    if($list_v['all_money']>0){
                        $lists[$list_k]['profit_rate'] = round($lists[$list_k]['profit']/$list_v['all_money']*100,2);
                    }else{
                        $lists[$list_k]['profit_rate'] = 0;
                    }
                    $lists[$list_k]['net_profit'] = round($lists[$list_k]['profit']-$list_v['preferential_money']-$list_v['purchase_money'],$price_decimal);
                    if($list_v['all_money']>0){
                        $lists[$list_k]['net_profit_rate'] = round($lists[$list_k]['net_profit']/$list_v['all_money']*100,2);
                    }else{
                        $lists[$list_k]['net_profit_rate'] = 0;
                    }
                }

                foreach ($list as $list_k=>$list_v){
                    $status = true;
                    foreach ($lists as $lists_k=>$lists_v){
                        if($list_v['id']==$lists_v['id']){
                            $status = false;
                            $list[$list_k]['pay_money'] = $lists[$lists_k]['pay_money'];
                            $list[$list_k]['sales_cost'] = $lists[$lists_k]['sales_cost'];
                            $list[$list_k]['profit'] = $lists[$lists_k]['profit'];
                            $list[$list_k]['profit_rate'] = $lists[$lists_k]['profit_rate'];
                            $list[$list_k]['net_profit'] = $lists[$lists_k]['net_profit'];
                            $list[$list_k]['net_profit_rate'] = $lists[$lists_k]['net_profit_rate'];
                        }
                    }
                    if($status){
                        $cost_all = $list_v['sales_cost'];
                        $list[$list_k]['sales_cost'] = round($cost_all,$price_decimal);
                        $list[$list_k]['profit'] = round($list_v['all_money']-$cost_all,$price_decimal);
                        if($list_v['all_money']>0){
                            $list[$list_k]['profit_rate'] = round($list[$list_k]['profit']/$list_v['all_money']*100,2);
                        }else{
                            $list[$list_k]['profit_rate'] = 0;
                        }
                        $list[$list_k]['net_profit'] = round($list[$list_k]['profit']-$list_v['preferential_money']-$list_v['purchase_money'],$price_decimal);
                        if($list_v['all_money']>0){
                            $list[$list_k]['net_profit_rate'] = round($list[$list_k]['net_profit']/$list_v['all_money']*100,2);
                        }else{
                            $list[$list_k]['net_profit_rate'] = 0;
                        }
                    }
                }
            }

            $sale_user_data = Db::name('kuyou_staff_member')->column('name','id');
            $admin_data = Db::name('admin')->column('username','id');
            foreach ($list as $list_k=>$list_v){
                $list[$list_k]['sale_user'] = isset($sale_user_data[$list_v['sale_user']])?$sale_user_data[$list_v['sale_user']]:'';
                $list[$list_k]['preparation'] = isset($admin_data[$list_v['preparation_id']])?$admin_data[$list_v['preparation_id']]:'';
            }
            $price_decimal = \think\Db::name('kuyou_sets')->where(['name'=>'price_decimal'])->value('value');
            $all_money_all = 0;$profit_all = 0;$net_profit_add = 0;
            $number = 0;
            $amount = 0;
            $all_money = 0;
            $tax_money = 0;
            $money_tax_price = 0;
            $sales_cost = 0;
            $profit = 0;
            $preferential_money = 0;
            $purchase_money = 0;
            $net_profit = 0;
            $real_money = 0;
            $customers_money = 0;
            $need_money = 0;
            $all_pay_money = 0;
            foreach ($list as $list_k=>$list_v){
                $all_money_all += $list[$list_k]['all_money'];
                $profit_all += $list[$list_k]['profit'];
                $net_profit_add += $list[$list_k]['net_profit'];

                $number += $list_v['number'];
                $amount += $list_v['amount'];
                $all_money += $list[$list_k]['all_money'];
                $tax_money += $list_v['tax_money'];
                $money_tax_price += $list_v['money_tax_price'];
                $sales_cost += $list_v['sales_cost'];
                $profit += $list[$list_k]['profit'];
                $preferential_money += $list_v['preferential_money'];
                $purchase_money += $list_v['purchase_money'];
                $net_profit += $list[$list_k]['net_profit'];
                $real_money += $list_v['real_money'];
                $customers_money += $list_v['customers_money'];
                $need_money += $list_v['need_money'];
                $all_pay_money += $list_v['pay_money'];
            }

            if($all_money_all>0){
                $profit_rate_all = round($profit_all/$all_money_all*100,4);
            }else{
                $profit_rate_all = 0;
            }
            if($all_money_all>0){
                $net_profit_rate_all = round($net_profit_add/$all_money_all*100,4);
            }else{
                $net_profit_rate_all = 0;
            }

            $all['number'] = $number;
            $all['amount'] = $amount;
            $all['all_money'] = round($all_money,$price_decimal);
            $all['tax_money'] = round($tax_money,$price_decimal);
            $all['money_tax_price'] = round($money_tax_price,$price_decimal);
            $all['sales_cost'] = round($sales_cost,$price_decimal);
            $all['profit'] = round($profit,$price_decimal);
            $all['preferential_money'] = round($preferential_money,$price_decimal);
            $all['purchase_money'] = round($purchase_money,$price_decimal);
            $all['net_profit'] = round($net_profit,$price_decimal);
            $all['real_money'] = round($real_money,$price_decimal);
            $all['customers_money'] = round($customers_money,$price_decimal);
            $all['need_money'] = round($need_money,$price_decimal);
            $all['pay_money'] = round($all_pay_money,$price_decimal);
            $all['profit_rate'] = round($profit_rate_all,4);
            $all['net_profit_rate'] = round($net_profit_rate_all,4);

            $result = array("count" => $row_count, "list" => $list,'sum'=>$all);

            if(isset($result['list']) && isset($result['count'])){
                $this->success('查询成功',$result,200);
            }else{
                $this->error('查询失败','',406);
            }
        }else{
            $this->error('请求方式错误','',250);
        }
    }
}
